package com.ccteam.admin.view.fragments.banner

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ccteam.admin.R
import com.ccteam.admin.REFRESH_REQUEST_KEY
import com.ccteam.admin.core.ADD_TYPE
import com.ccteam.admin.core.EDIT_TYPE
import com.ccteam.admin.databinding.BannerHomeInfoItemBinding
import com.ccteam.admin.databinding.FragmentBannerHomeBinding
import com.ccteam.admin.viewmodels.banner.BannerHomeViewModel
import com.ccteam.model.artist.ArtistVO
import com.ccteam.model.banner.BannerVO
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author Xiaoc
 * @since 2021/3/26
 */
@AndroidEntryPoint
class BannerHomeFragment: Fragment() {

    private var _binding: FragmentBannerHomeBinding? = null
    private val binding get() = _binding!!

    private val bannerHomeViewModel by viewModels<BannerHomeViewModel>()

    private lateinit var adapter: BannerListRVAdapter

    companion object{
        val differCallback = object: DiffUtil.ItemCallback<BannerVO>(){

            override fun areItemsTheSame(oldItem: BannerVO, newItem: BannerVO): Boolean {
                return oldItem == newItem
            }

            override fun areContentsTheSame(oldItem: BannerVO, newItem: BannerVO): Boolean {
                return oldItem == newItem
            }

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentBannerHomeBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        adapter = BannerListRVAdapter(callback)
        binding.rvBanner.adapter = adapter

        viewLifecycleOwner.lifecycleScope.launch {
            bannerHomeViewModel.bannerListFlow.collectLatest {
                adapter.submitData(it)
            }
        }

        viewLifecycleOwner.lifecycleScope.launch {
            adapter.loadStateFlow.collectLatest { state ->
                binding.statusView.changeToLoadingStatus(state.refresh is LoadState.Loading)
                binding.statusView.changeToErrorStatus(state.refresh,
                    state.append.endOfPaginationReached && adapter.itemCount < 1)
                binding.refreshView.isRefreshing = state.refresh is LoadState.Loading
            }
        }

        binding.statusView.setRetryClickListener {
            adapter.refresh()
        }

        binding.refreshView.setOnRefreshListener {
            adapter.refresh()
        }

        binding.btnAdd.setOnClickListener {
            findNavController().navigate(BannerHomeFragmentDirections
                .actionBannerHomeFragmentToBannerDetailFragment(ADD_TYPE,null))
        }

    }

    override fun onResume() {
        super.onResume()

        setFragmentResultListener(REFRESH_REQUEST_KEY) { _, bundle ->
            if(bundle.getBoolean(REFRESH_REQUEST_KEY)){
                viewLifecycleOwner.lifecycleScope.launch {
                    delay(100L)
                    adapter.refresh()
                }
            }
        }
    }

    private val callback = object: BannerItemCallback{

        override fun itemClick(item: BannerVO) {
            findNavController().navigate(BannerHomeFragmentDirections
                .actionBannerHomeFragmentToBannerDetailFragment(EDIT_TYPE,item.id))
        }

    }

    /**
     * 基于分页 [PagingDataAdapter] 的RecyclerView 适配器
     */
    class BannerListRVAdapter(
        val callback: BannerItemCallback
    ): PagingDataAdapter<BannerVO, BannerListRVAdapter.BannerInfoViewHolder>(
        differCallback){

        inner class BannerInfoViewHolder(
            val binding: BannerHomeInfoItemBinding
        ): RecyclerView.ViewHolder(binding.root){
            var item: BannerVO? = null
            init {
                binding.root.setOnClickListener {
                    item?.let {
                        callback.itemClick(it)
                    }
                }
            }
        }

        override fun onBindViewHolder(holder: BannerInfoViewHolder, position: Int) {
            getItem(position)?.let {
                holder.item = it

                Glide.with(holder.binding.ivBanner)
                    .load(it.url)
                    .placeholder(R.drawable.img_default_album_big)
                    .into(holder.binding.ivBanner)
            }

        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BannerInfoViewHolder {
            return BannerInfoViewHolder(BannerHomeInfoItemBinding.inflate(LayoutInflater.from(parent.context),parent,false))
        }
    }

    /**
     * Album列表点击事件回调
     */
    interface BannerItemCallback{
        /**
         * 点击了轮播图Item
         */
        fun itemClick(item: BannerVO)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
